<template>
  <div class="cpt-comfy-taskitem shadow m-2 relative">

    <div class="pic  2 flex justify-center items-center border-1  " :style="customerStyle"
      v-if="!checkResult.status.completed">
      {{ taskFailed ? '排队的任务有点多，稍后再来吧' : '绘制中...' }}
    </div>
    <div class="pic" :style="customerStyle" v-for="(image, index) in checkResult.images" :key="index" v-else>
      <!-- <img :src="image" alt="生成图片" class="w-full h-full" /> -->
      <el-image style="width: 100%; height: 100%" :src="image" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
        @click="handleImagePreview" :preview-src-list="[image]" :initial-index="4" fit="cover" />
    </div>
    <div
      class="cpt-comfy-taskitem-menu flex justify-around items-center absolute bottom-0 left-0 w-full py-2 text-white"
      :class="[{ valid: checkResult.status.completed }]">
      <div class="menu-mask absolute w-full h-full bg-[#333] opacity-64 blur-[1px] rounded-lt-sm rounded-rt-sm"></div>
      <div class="btn cursor-pointer rounded-md px-2 py-1 bg-[#1D255A] relative" @click="clickPubWorkinfo"
        v-if="!taskItem?.workinfos?.length">发布</div>
      <div class="btn cursor-pointer rounded-md px-2 py-1 bg-[#1D255A] opacity-50 relative" v-else>已发布
      </div>
      <div class="btn  cursor-pointer rounded-md px-2  py-1 bg-[#9DBFFB] relative" @click="clickDownloadImage">下载</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { BASE_URL, postCheckPromptDetail } from '../../service/yapi';
import { defineEmits } from 'vue'
import OptimizedImage from '~/components/OptimizedImage.vue'

const props = defineProps({
  taskItem: {
    type: Object,
    required: true
  },
  width: {
    type: Number,
    default: 120
  },
  height: {
    type: Number,
    default: 120
  }
})
let customerStyle = computed(() => {
  return {
    width: props.width + 'px',
    height: props.height + 'px'
  }
})
let taskIntervalInstance = ref<any>(null)
let emits = defineEmits(['clickPubWorkinfo', 'downloadImage'])
let checkTimes = ref(0) // 添加计数变量
let taskFailed = ref(false) // 添加失败状态变量
let clickPubWorkinfo = () => {
  console.log("%c Line:53 🥒 props", "color:#6ec1c2", props);
  if (props.taskItem?.id) {

    emits('clickPubWorkinfo', { taskItem: props.taskItem, checkResult: checkResult.value })
  } else {
    emits('clickPubWorkinfo', { taskItem: { ...props.taskItem, id: checkResult.value.id }, checkResult: checkResult.value })

  }

}
let maxCheckTimes = 10 // 修改为10次
let checkResult = ref<any>({
  status: {
    completed: false,
  },
  id: "",
  images: []

})
let checkTaskStatus = async () => {
  if (checkResult.value.status.completed) {
    console.log('清除计时器')
    clearInterval(taskIntervalInstance.value)
  } else {
    // 增加检查次数
    checkTimes.value += 1
    
    // 如果检查次数超过最大次数，标记任务失败并清除计时器
    if (checkTimes.value > maxCheckTimes) {
      console.log('任务检查超过10次，可能失败')
      taskFailed.value = true
      clearInterval(taskIntervalInstance.value)
      return
    }
    
    let res: any = await postCheckPromptDetail({ prompt_id: props.taskItem.prompt_id })
    if (res.code == 1000) {
      console.log("%c Line:31 🍇 res", "color:#4fff4B", res);
      let { status, outputPic, outputType, id } = res.data
      if (outputType == 'comfyuiServer') {
        checkResult.value = {
          status,
          id,
          images: outputPic.map((image: any) => {
            let url = `${BASE_URL}/comfyui/appuser/comm/previewImage?url=${image.filename}`
            return url
          })
        }
      } else {
        checkResult.value = {
          id,
          status,
          images: [outputPic]
        }
      }

      console.log('检查任务状态')
    }


  }
}
let clickDownloadImage = () => {
  emits('downloadImage', props.taskItem)
  console.log("%c Line:95 🥟 props.taskItem", "color:#f5ce50", props.taskItem);
}
let handleImagePreview = () => {
  nextTick(() => {
    // 获取遮罩层dom
    let domImageMask = document.querySelector('.el-image-viewer__mask')
    if (!domImageMask) {
      return
    }
    domImageMask.addEventListener('click', () => {
      // 点击遮罩层时调用关闭按钮的 click 事件
      // @ts-ignore
      document.querySelector('.el-image-viewer__close').click()
    })
  })
}
onMounted(() => {
  console.log('组件循环渲染')
  if (props.taskItem?.status?.completed) {
    checkResult.value = {
      status: props.taskItem.status,
      images: props.taskItem.outputPics.split(',')
    }
    return
  }
  // 重置检查次数和失败标记
  checkTimes.value = 0
  taskFailed.value = false
  
  taskIntervalInstance.value = setInterval(() => {

    checkTaskStatus()
  }, 1000)
})
</script>
<style lang="scss">
.cpt-comfy-taskitem {

  .cpt-comfy-taskitem-menu {
    display: none;
  }

  &:hover {
    .cpt-comfy-taskitem-menu.valid {
      display: flex;
    }
  }
}
</style>